const LinkedNode = require('./linkedNode').LinkedNode;

/**
 * 顺序表
 * 
 * @author shuyuan.dai 2021-02-05
 */
class SequentialArray {
    constructor(arr = []) {
        this.arr = arr;
    }

    transfer2LinkedList() {
        if (this.arr.length <= 0) {
            return null;
        }

        let linkedList = new LinkedNode(this.arr[0]);
        for (let p = linkedList, i = 1; i < this.arr.length; ++i) {
            p = p.add(this.arr[i]);
        }

        return linkedList;
    }

    swap(i, j) {
        let temp = this.arr[i];
        this.arr[i] = this.arr[j];
        this.arr[j] = temp;
    }

    insert(i, v) {
        if (i < 0 || i >= this.arr.length) {
            return false;
        }

        for (let k = this.arr.length; k > i; --k) {
            this.arr[k] = this.arr[k - 1];
        }

        this.arr[i] = v;
        return true;
    }

    set(i, v) {
        this.arr[i] = v;
    }

    elementInIndex(i) {
        return this.arr[i];
    }

    removeByIndex(i) {
        if (i < 0 || i >= this.arr.length) {
            return false;
        }

        for (let k = i + 1; k < this.arr.length; ++k) {
            this.arr[k - 1] = this.arr[k];
        }

        this.arr.length--;
        return true;
    }

    removeByValue(v) {
        for(let i=0; i < this.arr.length; ++i) {
            if(this.arr[i] == v) {
                this.removeByIndex(i);
            }
        }
    }

    toString() {
        return `arr[${this.arr.length}]=${this.arr.join(",")}`;
    }
}

exports.SequentialArray = SequentialArray;